package edu.zcmu.seckill.exception;

import edu.zcmu.seckill.response.R;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * @Author: tang
 * @Date: 2022/02/17/15:42
 * @Description: 统一异常处理类
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(MyException.class)
    @ResponseBody
    public R error(MyException e){
        return R.error().message(e.getMsg()).code(e.getCode());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public R error(MethodArgumentNotValidException e){

        List<ObjectError> errorList=e.getBindingResult().getAllErrors();
        String error="";
        for (ObjectError objectError : errorList) {
            error=objectError.getDefaultMessage();
        }
        return R.error().message(error);
    }
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public R error(Exception e){
        String message = e.getMessage();
        return R.error().message(message);
    }
}
